package cn.xspace.app.filemg.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xspace.android.xafcommon.util.BaseRProxy;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.view.MyFragmentPagerAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.xspace.app.filemg.bean.ChooseFileInfo;
import cn.xspace.app.filemg.bean.FileInfo;
import cn.xspace.app.filemg.fragment.FileAppFragment;
import cn.xspace.app.filemg.fragment.FileDocFragment;
import cn.xspace.app.filemg.fragment.FileImgFragment;
import cn.xspace.app.filemg.fragment.FileMusicFragment;
import cn.xspace.app.filemg.fragment.FileOtherFragment;
import cn.xspace.app.filemg.util.CallBack;
import cn.xspace.app.filemg.util.FileMg;
import de.greenrobot.event.EventBus;

public class FileActivity extends FragmentActivity implements CallBack,
        OnClickListener {

    public static final String TAG = FileActivity.class.getSimpleName();

    protected TextView mImageRight;
    protected TextView mImageLeft;
    protected View mTitleLayout;
    private Button btnStart;
    private TextView tv_chose_size;
    private TextView mTitle;
    private TextView mApp, mImg, mMusic, mDoc, mAll;
    private ImageView mTableImg1;
    private ImageView mTableImg2;
    private ImageView mTableImg3;
    private ImageView mTableImg4;
    private ImageView mTableImg5;
    private ViewPager mPager;
    private ArrayList<Fragment> fragmentsList;
    private FileAppFragment mFileAppFragment;
    private FileImgFragment mFileImgFragment;
    private FileMusicFragment mFileMusicFragment;
    private FileDocFragment mFileDocFragment;
    private FileOtherFragment mFolderFragment;
    private int currIndex = 0;
    private Resources resources;
    private Drawable mDrawable, mDrawableBg;
    private boolean isEixt = true;
    private ArrayList<FileInfo> checkList;
    private long fileSize = 0;
    private int number = 0;
    private Button mButton;
    private Handler mHandler = new Handler();
    private boolean findFlag = true;
    private ProgressDialog progressDialog;
    private int findTime = 30;
    private boolean continueFlag = false;
    private HashMap<Integer, ImageView> imgMap = new HashMap<Integer, ImageView>();
    private HashMap<Integer, TextView> textMap = new HashMap<Integer, TextView>();
    private ChooseFileInfo chooseInfo = new ChooseFileInfo();
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(BaseRProxy.file_main);
        resources = getResources();
        context = this;
        EventBus.getDefault().register(context);
        checkList = new ArrayList<FileInfo>();
        progressDialog = new ProgressDialog(this);
        initTopView();
        initTextView();
    }

    protected void initTopView() {
        findViewById(BaseRProxy.r_item).setBackgroundResource(BaseRProxy.getSkinID());
        mImageLeft = (TextView) findViewById(BaseRProxy.img_left);
        mImageRight = (TextView) findViewById(BaseRProxy.img_right);
        mTitle = (TextView) findViewById(BaseRProxy.title);
        mImageRight.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mImageLeft.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(FileActivity.this,
                        FileAllActivity.class);
                intent1.putExtra("chooseInfo", chooseInfo);
//				startActivityForResult(intent1, 120);
                startActivity(intent1);
            }
        });

        mTitle.setText("文件");
    }

    private void initTextView() {
        mButton = (Button) findViewById(BaseRProxy.btnStart);

        mTableImg1 = (ImageView) findViewById(BaseRProxy.sms_table_img1);
        mTableImg2 = (ImageView) findViewById(BaseRProxy.sms_table_img2);
        mTableImg3 = (ImageView) findViewById(BaseRProxy.sms_table_img3);
        mTableImg4 = (ImageView) findViewById(BaseRProxy.sms_table_img4);
        mTableImg5 = (ImageView) findViewById(BaseRProxy.sms_table_img5);
        mApp = (TextView) findViewById(BaseRProxy.type_app);
        mImg = (TextView) findViewById(BaseRProxy.type_img);
        mMusic = (TextView) findViewById(BaseRProxy.type_music);
        mDoc = (TextView) findViewById(BaseRProxy.type_doc);
        mAll = (TextView) findViewById(BaseRProxy.type_all);
        imgMap.put(0, mTableImg1);
        imgMap.put(1, mTableImg2);
        imgMap.put(2, mTableImg3);
        imgMap.put(3, mTableImg4);
        imgMap.put(4, mTableImg5);

        textMap.put(0, mMusic);
        textMap.put(1, mImg);
        textMap.put(2, mDoc);
        textMap.put(3, mApp);
        textMap.put(4, mAll);

        mPager = (ViewPager) findViewById(BaseRProxy.vPager);
        fragmentsList = new ArrayList<Fragment>();
        mFileAppFragment = FileAppFragment.newInstance(this);
        mFileImgFragment = FileImgFragment.newInstance(this);
        mFileMusicFragment = FileMusicFragment.newInstance(this);
        mFileDocFragment = FileDocFragment.newInstance(this);
        mFolderFragment = FileOtherFragment.newInstance(this);
        fragmentsList.add(mFileMusicFragment);
        fragmentsList.add(mFileImgFragment);
        fragmentsList.add(mFileDocFragment);
        fragmentsList.add(mFileAppFragment);

        fragmentsList.add(mFolderFragment);
        mApp.setOnClickListener(new MyOnClickListener(3));
        mImg.setOnClickListener(new MyOnClickListener(1));
        mMusic.setOnClickListener(new MyOnClickListener(0));
        mDoc.setOnClickListener(new MyOnClickListener(2));
        mAll.setOnClickListener(new MyOnClickListener(4));
        mPager.setAdapter(new MyFragmentPagerAdapter(
                getSupportFragmentManager(), fragmentsList));
        mPager.setCurrentItem(0);
        mPager.setOnPageChangeListener(new MyOnPageChangeListener());
        tv_chose_size = (TextView) findViewById(BaseRProxy.tv_chose_size);
        btnStart = (Button) findViewById(BaseRProxy.btnStart);
    }

    @Override
    public void onDestroy() {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
        EventBus.getDefault().unregister(context);
    }

    public class MyOnClickListener implements OnClickListener {
        private int index = 0;

        public MyOnClickListener(int i) {
            index = i;
        }

        @Override
        public void onClick(View v) {
            try {
                mPager.setCurrentItem(index);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    ;

    public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageSelected(int arg0) {
            try {
                changeColor(arg0);
                mPager.setCurrentItem(arg0);
                currIndex = arg0;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    }

    private void changeColor(int currIndex) {
        for (int i = 0; i < 5; i++) {
            if (i == currIndex) {
                imgMap.get(i).setVisibility(View.VISIBLE);
                textMap.get(i).setTextColor(
                        getResources().getColor(BaseRProxy.sms_black));
            } else {
                imgMap.get(i).setVisibility(View.GONE);
                textMap.get(i).setTextColor(
                        getResources().getColor(BaseRProxy.sms_gray_bold));
            }
        }
    }

    private void stopActivity() {
        // if (findFlag) {
        // progressDialog.setMessage(this.getString(R.string.find_file_stop));
        // progressDialog.show();
        // }
        // finish();
    }

    public void returnPage(View v) {
        stopActivity();
    }

    public void sendFile(View v) {
        // if (number <= 0) {
        // Toast.makeText(this, R.string.choice_file_err, Toast.LENGTH_SHORT)
        // .show();
        // return;
        // }
        // findFlag = false;
        // if (continueFlag) {
        // mServer.sendFiles(mUserBean, checkList);
        // Intent intent = new Intent(this, SendFileActivity.class);
        // intent.putExtra(SendFileActivity.EXTRA_USER, mUserBean);
        // startActivity(intent);
        // } else {
        // Intent intent = new Intent();
        // intent.setClass(this, ChoicePhoneActivity.class);
        // intent.putExtra("fileSize", fileSize);
        // intent.putExtra("number", number);
        // intent.putCharSequenceArrayListExtra("list", (ArrayList) checkList);
        // startActivity(intent);
        // }
        // stopActivity();
    }

    @Override
    public void checkedInfo(FileInfo info) {
        if (info.getPath() == null || "".equals(info.getPath())) {
            return;
        }
        if (!info.isCheckFlag()) {
            for (FileInfo fInfo : chooseInfo.getFileList()) {
                if (info.getPath().equals(fInfo.getPath())) {
                    chooseInfo.removeFileSize(info.getSize());
                    chooseInfo.getFileList().remove(fInfo);
                    break;
                }
            }
        } else {
            chooseInfo.addFileSize(info.getSize());
            chooseInfo.getFileList().add(info);
        }
        initButton();
    }

    private void initButton() {
        tv_chose_size.setText(FileMg.FormetFileSize(chooseInfo.getSize()));
        if (chooseInfo.getFileList().size() > 0) {
            btnStart.setText("发送(" + chooseInfo.getFileList().size() + ")");
        } else {
            btnStart.setText("发送");
        }
        mFileAppFragment.initChooseData(chooseInfo);
        mFileMusicFragment.initChooseData(chooseInfo);
        mFileImgFragment.initChooseData(chooseInfo);
        mFileDocFragment.initChooseData(chooseInfo);
        mFolderFragment.initChooseData(chooseInfo);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 120 && resultCode == RESULT_OK) {
            chooseInfo = (ChooseFileInfo) data
                    .getSerializableExtra("chooseInfo");
            boolean isSend = data.getBooleanExtra("isSend", false);
            if (isSend) {
                Intent mIntent = new Intent();
                mIntent.putExtra("chooseInfo", chooseInfo);
                mIntent.putExtra("isSend", true);
                setResult(RESULT_OK, mIntent);
                finish();
            } else {
                initButton();
            }
        }
    }

    public void onEventMainThread(Map<String, Object> map) {
        if ("FileAllActivity".equals(map.get("type"))) {
            chooseInfo = (ChooseFileInfo) map.get("chooseInfo");
            boolean isSend = (Boolean) map.get("isSend");
            if (isSend) {
                map = new HashMap<>();
                map.put("chooseInfo", chooseInfo);
                map.put(EventBusConstant.TYPE, TAG);
                EventBus.getDefault().post(map);
                finish();
            } else {
                initButton();
            }
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v.getId() == BaseRProxy.btnStart) {
            /*if(!AppUtil.isConnected(context)){
                Toast.makeText(this, "当前网络未连接,请检查网络连接后重试", Toast.LENGTH_SHORT).show();
			}
			else */
            if (chooseInfo.getFileList().size() == 0) {
                Toast.makeText(this, "请选择文件", Toast.LENGTH_SHORT).show();
            } else {
//				Intent mIntent = new Intent();
//				mIntent.putExtra("chooseInfo", chooseInfo);
//				mIntent.putExtra("isSend", true);
//				setResult(RESULT_OK, mIntent);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put(EventBusConstant.TYPE, TAG);
                map.put("chooseInfo", chooseInfo);
                map.put("isSend", true);
                EventBus.getDefault().post(map);
                finish();
            }

        }

    }
}
